#include <linux/types.h>
#include <linux/tty.h>

static struct tty_buffer *tty_buffer_alloc(struct tty_struct *tty, size_t size)
{
	struct tty_buffer *p;
	// printf("this is %s(): %d\r\n", __func__, __LINE__);

	if (tty->buf.memory_used + size > 65536)
		return NULL;
	p = kmalloc(sizeof(struct tty_buffer) + 2 * size);
	if (p == NULL)
		return NULL;
	p->used = 0;
	p->size = size;
	p->next = NULL;
	p->commit = 0;
	p->read = 0;
	p->char_buf_ptr = (char *)(p->data);
	p->flag_buf_ptr = (unsigned char *)p->char_buf_ptr + size;
	tty->buf.memory_used += size;
	// printf("this is %s(): %d\r\n", __func__, __LINE__);
	return p;
}

static struct tty_buffer *tty_buffer_find(struct tty_struct *tty, size_t size)
{
	struct tty_buffer **tbh = &tty->buf.free;
	while ((*tbh) != NULL) {
		struct tty_buffer *t = *tbh;
		if (t->size >= size) {
			*tbh = t->next;
			t->next = NULL;
			t->used = 0;
			t->commit = 0;
			t->read = 0;
			tty->buf.memory_used += t->size;
			return t;
		}
		tbh = &((*tbh)->next);
	}
	/* Round the buffer size out */
	size = (size + 0xFF) & ~0xFF;
	return tty_buffer_alloc(tty, size);
	/* Should possibly check if this fails for the largest buffer we
	   have queued and recycle that ? */
}

int tty_buffer_request_room(struct tty_struct *tty, size_t size)
{
	struct tty_buffer *b, *n;
	int left;
	unsigned long flags;

	// spin_lock_irqsave(&tty->buf.lock, flags);

	/* OPTIMISATION: We could keep a per tty "zero" sized buffer to
	   remove this conditional if its worth it. This would be invisible
	   to the callers */
	if ((b = tty->buf.tail) != NULL)
		left = b->size - b->used;
	else
		left = 0;

	if (left < size) {
		/* This is the slow path - looking for new buffers to use */
		if ((n = tty_buffer_find(tty, size)) != NULL) {
			// printf("this is %s(): %d  \r\n", __func__, __LINE__);
			if (b != NULL) {
				b->next = n;
				b->commit = b->used;
				// printf("this is %s(): %d  b->commit = %d\r\n", __func__, __LINE__, b->commit);
			} else
				tty->buf.head = n;
			tty->buf.tail = n;
		} else
			size = left;
	}

	// spin_unlock_irqrestore(&tty->buf.lock, flags);
	return size;
}

int tty_insert_flip_string_flags(struct tty_struct *tty,
		const unsigned char *chars, const char *flags, size_t size)
{
	int copied = 0;
	do {
		int space = tty_buffer_request_room(tty, size - copied);
		struct tty_buffer *tb = tty->buf.tail;
		/* If there is no space then tb may be NULL */
		if (space == 0)
			break;
		memcpy(tb->char_buf_ptr + tb->used, chars, space);
		memcpy(tb->flag_buf_ptr + tb->used, flags, space);
		// printf("this is %s(): %d  space = %d, tb->char_buf_ptr = %c\r\n", __func__, __LINE__, space, tb->char_buf_ptr[tb->used]);
		tb->used += space;
		copied += space;
		chars += space;
		flags += space;
		/* There is a small chance that we need to split the data over
		   several buffers. If this is the case we must loop */
	} while (size > copied);
	return copied;
}

int tty_insert_flip_char(struct tty_struct *tty, unsigned char ch, char flag)
{
	struct tty_buffer *tb = tty->buf.tail;
	if (tb && tb->used < tb->size) {
		// printf("this is %s(): %d  tb->used = %d, tb->size = %d\r\n", __func__, __LINE__, tb->used, tb->size);
		tb->flag_buf_ptr[tb->used] = flag;
		tb->char_buf_ptr[tb->used++] = ch;
		// printf("this is %s(): %d  tb->char_buf_ptr = %c\r\n", __func__, __LINE__, tb->char_buf_ptr[tb->used-1]);
		return 1;
	}
	return tty_insert_flip_string_flags(tty, &ch, &flag, 1);
}

void tty_flip_buffer_push(struct tty_struct *tty)
{
	unsigned long flags;
	// spin_lock_irqsave(&tty->buf.lock, flags);
	if (tty->buf.tail != NULL)
		tty->buf.tail->commit = tty->buf.tail->used;
	// spin_unlock_irqrestore(&tty->buf.lock, flags);

	flush_to_ldisc(tty);
}

static void tty_buffer_free(struct tty_struct *tty, struct tty_buffer *b)
{
	/* Dumb strategy for now - should keep some stats */
	tty->buf.memory_used -= b->size;
	// WARN_ON(tty->buf.memory_used < 0);

	if (b->size >= 512)
		kfree(b);
	else {
		b->next = tty->buf.free;
		tty->buf.free = b;
	}
}

void flush_to_ldisc(struct tty_struct *tty)
{
	unsigned long 	flags;

    struct tty_buffer *head;
    while ((head = tty->buf.head) != NULL) {
        int count;
        char *char_buf;
        unsigned char *flag_buf;

        count = head->commit - head->read;
        if (!count) {
            if (head->next == NULL)
                break;
            tty->buf.head = head->next;
            tty_buffer_free(tty, head);
            continue;
        }
        // if (!tty->receive_room) {
        //     schedule_delayed_work(&tty->buf.work, 1);
        //     break;
        // }
        // if (count > tty->receive_room)
        //     count = tty->receive_room;
        char_buf = head->char_buf_ptr + head->read;
        flag_buf = head->flag_buf_ptr + head->read;
        head->read += count;

        n_tty_receive_buf(tty, char_buf, flag_buf, count);
    }
}

void tty_flush_to_ldisc(struct tty_struct *tty)
{
	// flush_delayed_work(&tty->buf.work);
	flush_to_ldisc(tty);
}

void tty_buffer_init(struct tty_struct *tty)
{
	// spin_lock_init(&tty->buf.lock);
	tty->buf.head = NULL;
	tty->buf.tail = NULL;
	tty->buf.free = NULL;
	tty->buf.memory_used = 0;
	// INIT_DELAYED_WORK(&tty->buf.work, flush_to_ldisc);
}
